import { createRouter, createWebHashHistory } from "vue-router";
import type { RouteRecordRaw } from 'vue-router'
import { useRouterStore } from "./stores/router";
import { useUserStore } from "./stores/user";

/**
 * 定义路由规则
 * 路由规则中的 name 字段必须跟组件名称相同(文件名相同), 否则 KeepAlive 无法生效
 */
export const routes: IRouteRecord<RouteRecordRaw>[] = [
  {
    name: 'login',
    path: '/login',
    component: () => import('#/auth/login.vue')
  },
  {
    name: 'redirect',
    path: '/redirect',
    component: () => import('#/redirect/redirect.vue')
  },
  {
    name: 'menu',
    path: '/',
    component: () => import('@/layout/layout.vue'),
    redirect: '/home',
    children: [
      {
        name: 'home',
        path: 'home',
        component: () => import('#/home/home.vue'),
        meta: {
          label: '主页',
          permissions: '*'
        }
      },
      {
        name: 'shop',
        path: 'shop',
        component: () => import('#/shop/shop.vue'),
        meta: {
          label: '店铺管理',
          permissions: '*',
          roles: [1]
        }
      },
      {
        name: 'order',
        path: 'order',
        meta: {
          label: '订单管理'
        },
        children: [
          {
            name: 'merchant-order-list',
            path: 'merchant-order-list',
            component: () => import('#/merchant-order-list/merchant-order-list.vue'),
            meta: {
              label: '订单列表',
              permissions: '*',
              roles: [1]
            }
          },
          {
            name: 'supporter-orders',
            path: 'supporter-orders',
            component: () => import('#/supporter-orders/supporter-orders.vue'),
            meta: {
              label: '订单列表',
              permissions: '*',
              roles: [2]
            }
          },
          {
            name: 'supporter-post-orders',
            path: 'supporter-post-orders',
            component: () => import('#/supporter-post-orders/supporter-post-orders.vue'),
            meta: {
              label: '打单发货',
              permissions: '*',
              roles: [2]
            }
          }
        ]
      },
      {
        name: 'settings',
        path: 'settings',
        meta: {
          label: '配置管理',
          roles: [2]
        },
        children: [
          {
            name: 'supporter-waybill',
            path: 'supporter-waybill',
            component: () => import('#/supporter-waybill/supporter-waybill.vue'),
            meta: {
              label: '电子面单管理',
              roles: [2]
            }
          },
          {
            name: 'supporter-waybill-template',
            path: 'supporter-waybill-template',
            component: () => import('#/supporter-waybill-template/supporter-waybill-template.vue'),
            meta: {
              label: '快递单模板管理',
              roles: [2]
            }
          }
        ]
      }
    ]
  }
]

// 注册测试路由
// if (import.meta.env.DEV) {
//   routes[1].children?.push({
//     name: 'test',
//     path: 'test',
//     meta: {
//       label: '组件测试',
//       permissions: '*'
//     },
//     children: [
//       {
//         name: 'template-editor-e2e',
//         path: 'template-editor-e2e',
//         component: () => import('@/test/template-editor-e2e.vue'),
//         meta: {
//           label: '模板编辑器E2E',
//           permissions: '*'
//         }
//       }
//     ]
//   })
// }

export const router = createRouter({
  history: createWebHashHistory(),
  routes
})

export interface IPermissionMatcher {
  (permission: RoutePermissions, user: IUser | undefined, meta: RouteMeta): boolean
}

// 权限匹配器, 用于判断路由权限是否匹配
export const PermissionMatcher: IPermissionMatcher = (permission, user, meta) => {
  // 登录状态
  if (permission !== '-' && !user) {
    return false
  }
  // 判断角色
  if (meta.roles?.length && !meta.roles.includes(user?.role_type)) {
    return false
  }
  return true
}

router.beforeEach(async (to) => {
  // 路由守卫, 检查用户权限和是否登录
  const routerStore = useRouterStore()
  const userStore = useUserStore()
  const meta: RouteMeta = to.meta

  if (to.name === 'login') {
    // 前往登录页面时清空路由缓存和用户数据
    console.log('clear user storage')
    routerStore.clear()
    userStore.clear()
    return true
  } else {
    // 路由权限校验
    let matched = false
    if (!meta.permissions || meta.permissions === '-' || (meta.permissions instanceof Array && meta.permissions.includes('-'))) {
      matched = true
    } else if (meta.permissions instanceof Array) {
      matched = !!meta.permissions.find(i => PermissionMatcher(i, userStore.user, meta))
    } else {
      matched = PermissionMatcher(meta.permissions, userStore.user, meta)
    }
    
    if (!matched) return '/login'

    routerStore.push({
      path: to.fullPath, 
      name: to.name as string, 
      meta: to.meta
    })
    return true
  }
})
